# -*- coding: utf-8 -*-

from core.serializers import CustomModelSerializer
from core.relations import UserNameWritableRelatedField
from apps.pms.models import Product
from rest_framework import serializers
from collections import defaultdict
from apps.sys.models import DictData


class ListProductSerializer(CustomModelSerializer):
    """
    产品管理-列表序列化器
    """

    owner_name = serializers.CharField(read_only=True, source="owner.name")
    mods_count = serializers.SerializerMethodField()
    vers_count = serializers.SerializerMethodField()
    reqs_count = serializers.SerializerMethodField()
    cases_count = serializers.SerializerMethodField()
    bugs_count = serializers.SerializerMethodField()

    def get_mods_count(self, instance):
        return len(instance.module_set.all())

    def get_vers_count(self, instance):
        return len(instance.version_set.all())

    def get_reqs_count(self, instance):
        return len(instance.requirement_set.all())

    def get_cases_count(self, instance):
        return len(instance.testcase_set.all())

    def get_bugs_count(self, instance):
        return len(instance.bug_set.all())

    class Meta:
        model = Product
        fields = "__all__"
        read_only_fields = ["id"]


class ProductSerializer(CustomModelSerializer):
    """
    产品管理-查询、新增、编辑序列化器
    """

    owner = UserNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )

    reqs_status = serializers.SerializerMethodField()
    cases_status = serializers.SerializerMethodField()
    bugs_status = serializers.SerializerMethodField()

    total_counts = serializers.SerializerMethodField()
    timed_counts = serializers.SerializerMethodField()

    def get_reqs_status(self, instance):
        status_counts = defaultdict(int)

        for requirement in instance.requirement_set.iterator():
            dict_map = DictData.objects.filter(
                type="pms_req_status", value=requirement.status
            ).first()
            status_name = dict_map.label if dict_map else None

            # 如果状态名存在，则增加其计数
            if status_name:
                status_counts[status_name] += 1

        # 将 defaultdict 转换为普通字典
        return [{"value": count, "name": name} for name, count in status_counts.items()]

    def get_cases_status(self, instance):
        status_counts = defaultdict(int)

        for testcase in instance.testcase_set.iterator():
            dict_map = DictData.objects.filter(
                type="tms_job_status", value=testcase.status
            ).first()
            status_name = dict_map.label if dict_map else None

            # 如果状态名存在，则增加其计数
            if status_name:
                status_counts[status_name] += 1

        # 将 defaultdict 转换为普通字典
        return [{"value": count, "name": name} for name, count in status_counts.items()]

    def get_bugs_status(self, instance):
        status_counts = defaultdict(int)

        for bug in instance.bug_set.iterator():
            dict_map = DictData.objects.filter(
                type="tms_bug_status", value=bug.status
            ).first()
            status_name = dict_map.label if dict_map else None

            # 如果状态名存在，则增加其计数
            if status_name:
                status_counts[status_name] += 1

        # 将 defaultdict 转换为普通字典
        return [{"value": count, "name": name} for name, count in status_counts.items()]

    def get_total_counts(self, instance):

        def get_items_count(items):
            return len(items)

        attr_names = ["requirement", "module", "version", "job", "testcase", "bug"]

        return {
            attr: get_items_count(getattr(instance, f"{attr}_set").all())
            for attr in attr_names
        }

    def get_timed_counts(self, instance):

        def get_items_count_by_createtime(items):
            createtime_counts = defaultdict(int)
            for bug in items:
                if bug.create_time:
                    date_key = bug.create_time.strftime("%Y-%m-%d")
                    createtime_counts[date_key] += 1

            return [
                {"value": count, "name": name}
                for name, count in createtime_counts.items()
            ]

        attr_names = ["requirement", "module", "version", "job", "testcase", "bug"]

        return {
            attr: get_items_count_by_createtime(
                getattr(instance, f"{attr}_set").iterator()
            )
            for attr in attr_names
        }

    class Meta:
        model = Product
        fields = "__all__"
        read_only_fields = ["id"]
